package com.shop.cereshop.admin.service.redis.impl;

import com.shop.cereshop.admin.dao.redis.CereRedisKeyDAO;
import com.shop.cereshop.admin.redis.service.api.StringRedisService;
import com.shop.cereshop.admin.service.redis.CereRedisKeyServcice;
import com.shop.cereshop.admin.thread.RedisKeyTask;
import com.shop.cereshop.commons.domain.redis.CereRedisKey;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class CereRedisKeyServciceImpl implements CereRedisKeyServcice {

    @Autowired
    private CereRedisKeyDAO cereRedisKeyDAO;

    @Autowired
    private StringRedisService stringRedisService;

    @Override
    public void add(String key, String endTime) throws CoBusinessException {
        CereRedisKey cereRedisKey=new CereRedisKey();
        cereRedisKey.setRedisKey(key);
        cereRedisKey.setEndTime(endTime);
        cereRedisKeyDAO.insert(cereRedisKey);
    }

    @Override
    public void updateByKey(String key, String endTime) throws CoBusinessException {
        //查询是否存在数据
        CereRedisKey byKey = cereRedisKeyDAO.findByKey(key);
        if(byKey!=null){
            //更新
            byKey.setRedisKey(key);
            byKey.setEndTime(endTime);
            cereRedisKeyDAO.updateByKey(byKey);
        }else {
            //新增
            CereRedisKey cereRedisKey=new CereRedisKey();
            cereRedisKey.setRedisKey(key);
            cereRedisKey.setEndTime(endTime);
            cereRedisKeyDAO.insert(cereRedisKey);
        }
    }

    @Override
    public void deleteByKey(String key) throws CoBusinessException {
        cereRedisKeyDAO.deleteByKey(key);
    }

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = {CoBusinessException.class, Exception.class})
    public void initializationRedis() throws Exception {
        //清空所有redis的key
        stringRedisService.deleteAll();
        //查询所有任务
        List<CereRedisKey> list=cereRedisKeyDAO.findAll();
        if(!EmptyUtils.isEmpty(list)){
            //将数据拆分成多个小的集合，开启多线程设置
            List<List<CereRedisKey>> split = EmptyUtils.split(list, 50);
            if(!EmptyUtils.isEmpty(split)){
                split.forEach(keys -> {
                    new Thread(new RedisKeyTask(keys,stringRedisService)).start();
                });
            }
        }
    }
}
